package com.plat.api.common.base;

import com.alibaba.fastjson.JSONObject;
import com.plat.api.common.RespCode;
import com.plat.api.exception.PlatException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/8/28
 * Time: 9:48
 * Description: No Description
 */
@Slf4j
public class ERROR {
    public static void error(HttpServletResponse rep, PlatException platException, String cmd) {
        OutputStream out = null;
        String msg = platException.getMessage();
        String code = platException.getCode();
        String desc = platException.getDesc();

        try {
            rep.setHeader("Content-type", "application/json");
            JSONObject json = new JSONObject(true);
            JSONObject body = new JSONObject(true);
            body.put("msg", msg);
            json.put("code", code);
            json.put("success", RespCode.FAIL.getError_msg());
            json.put("timestamp", new Date());
            json.put("msg", RespCode.FAIL.getError_msg());
            json.put("desc", desc);
            json.put("cmd", cmd);
            json.put("body", body);
            log.info("错误响应报文：" + json.toString());
            out = rep.getOutputStream();
            out.write(json.toString().getBytes("UTF-8"));
            out.flush();
        } catch (Exception e) {
            log.info("返回报文时异常");
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                log.info("关闭返回报文异常");
            }
        }
    }
}
